package common.permission

import models.UserM

object PermissionManager {
    private val map = mutableMapOf<String, MutableList<Int>>()

    fun addRoutePermissions(route: String, permissions: List<Int>){
        if (map[route] == null){
            map[route] = mutableListOf()
        }
        map[route]?.addAll(permissions)
    }

    private fun getRoutePermissions(route: String): List<Int>? {
        return map[route]
    }

    fun addUserPermission(state: Int, permission: Int): Int{
        return Permission.addPermission(state, permission)
    }

    fun removeUserPermission(state: Int, permission: Int): Int {
        return Permission.removePermission(state, permission)
    }

    fun checkUserPermission(userId: Int, permission: Int): Boolean {
        return checkUserPermissions(userId, listOf(permission))
    }

    fun checkUserPermissions(userId: Int, permissions: List<Int>): Boolean{
        val user = UserM.AGENT.findById(userId)
        val state = user?.getInt(UserM.STATE) ?: 0
        permissions.forEach { permission ->
           if (!Permission.hasPermission(state, permission)){
               return false
           }
        }
        return true
    }

    fun checkPermission(state: Int, permission: Int): Boolean {
        return Permission.hasPermission(state, permission)
    }

    fun checkPermissions(state: Int, permissions: List<Int>): Boolean{
        permissions.forEach {
            if (!Permission.hasPermission(state, it)){
                return false
            }
        }
        return true
    }

    fun getUserDefaultPermission(): Int{
        return Permission.initUserDefaultPermission()
    }
}